

package cn.shengchao.examstar.product.acl.adapters.repositories.factories;

import cn.hutool.core.util.StrUtil;
import cn.shengchao.examstar.product.domain.entity.Product;
import cn.shengchao.examstar.product.domain.valobj.Price;
import cn.shengchao.examstar.product.domain.valobj.ProductName;
import cn.shengchao.examstar.product.infrastructure.dao.po.BaseProduct;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Date;

/**
 * 产品抽象工厂
 */
public abstract class AbstractProductFactory<T extends BaseProduct, U extends Product> {

    /**
     * 预处理数据
     */
    protected abstract U initProduct(T datasource);

    /**
     * 创建缩略产品
     */
    public U createThumbnailProduct(T datasource) {
        U product = initProduct(datasource);
        product.setId(datasource.getId());
        product.setName(ProductName.of(datasource.getName()));
        product.setPrice(Price.of(datasource.getPrice()));
        if (datasource.getDiscountPrice() == null) {
            //如果折扣价不存在，则使用原价
            product.setDiscountPrice(Price.of(datasource.getPrice()));
        } else {
            product.setDiscountPrice(Price.of(datasource.getDiscountPrice()));
        }
        product.setDescription(datasource.getDescription());
        product.setDetails(datasource.getDetails());
        if (StrUtil.isNotEmpty(datasource.getSpecificationType())) {
            //字符串转数组
            product
                    .setSpecificationType(Arrays
                            .asList(datasource.getSpecificationType().split(",")));
        }
        product.setImageUrl(datasource.getImageUrl());
        product.setScore(datasource.getScore());
        product.setSort(datasource.getSort());
        product.setStatus(datasource.getStatus());
        product.setVirtualPurchaseNum(datasource.getVirtualPurchaseNum());
        product.setActualPurchaseNum(datasource.getActualPurchaseNum());
        product.setIsVirtual(datasource.getIsVirtual());
        if (datasource.getCreateTime() == null) {
            product.setCreateTime(new Date());
        } else {
            LocalDateTime createTime = datasource.getCreateTime();
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zdt = createTime.atZone(zoneId);
            Date date = Date.from(zdt.toInstant());
            product.setCreateTime(date);
        }
        product.setIsLogistics(datasource.getIsLogistics());
        return product;
    }

    /**
     * 创建产品
     */
    public U createProduct(T datasource) {
        U product = createThumbnailProduct(datasource);
        return afterCreateProduct(product);
    }

    /**
     * 后置处理数据
     */
    protected abstract U afterCreateProduct(U product);
}
